package com.castle.fortress.admin.flowable.delegate;

import cn.hutool.core.util.StrUtil;
import com.castle.fortress.admin.flowable.enums.ApproveStatusEnum;
import com.castle.fortress.admin.flowable.service.FlowableManageService;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.utils.CommonUtil;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 用户任务完成监听器
 * @author castle
 */
@Service
public class FortressUserTaskCompleteListener implements TaskListener {
    @Autowired
    private FlowableManageService flowableManageService;
    @Autowired
    private RuntimeService runtimeService;
    //拒绝后的审批类型
    private Expression refuseType;
    //是否是连续领导审批
    private Expression leadersLoop;

    @Override
    public void notify(DelegateTask delegateTask) {
        System.out.println("--------FortressUserTaskCompleteListener--------");
        String approveStatus = CommonUtil.emptyIfNull(delegateTask.getVariable("approveStatus"));
        System.out.println("任务节点："+delegateTask.getName()+"审批结果："+approveStatus);
        System.out.println("拒绝方式："+refuseType.getExpressionText());
        //审批拒绝时
        if(YesNoEnum.NO.getCode().toString().equals(approveStatus)){
            String refuse = refuseType.getExpressionText();
            //上一个审批节点
            if("PRE_NODE".equals(refuse)){
                System.out.println("任务节点："+delegateTask.getEventName()+"返回上个审批节点");
                flowableManageService.backToPreUserTask(delegateTask.getProcessInstanceId(),delegateTask.getTaskDefinitionKey(),delegateTask.getExecutionId(),delegateTask.getVariable("tid",String.class),delegateTask.getVariable("id",String.class));
            //结束流程
            }else if("ENDED_PRO".equals(refuse)){
                System.out.println("任务节点："+delegateTask.getEventName()+"结束流程");
                flowableManageService.endProcess(delegateTask.getProcessInstanceId(),delegateTask.getVariable("tid",String.class),delegateTask.getVariable("id",String.class), ApproveStatusEnum.UNAPPROVED.getCode()+"");
            //通过节点 则审批为通过
            }else if("TO_PASS".equals(refuse)){
                delegateTask.setVariable("approveStatus",YesNoEnum.YES.getCode().toString());
            }
        //判断是否是连续领导审批
        }else if(leadersLoop!=null){
            String loopFlag = leadersLoop.getExpressionText();
            //已完成的实例总数
            Integer nrOfCompletedInstances= delegateTask.getVariable("nrOfCompletedInstances")==null?0:Integer.parseInt(delegateTask.getVariable("nrOfCompletedInstances").toString());
            //实例总数
            Integer nrOfInstances= Integer.parseInt(delegateTask.getVariable("nrOfInstances").toString());
            boolean flag = false;
            //或签
            if("APPROVE_OR".equals(loopFlag)){
                if(nrOfCompletedInstances>=0){
                    flag=true;
                }
            }else if("APPROVE_AND".equals(loopFlag)){
                if(nrOfCompletedInstances==(nrOfInstances-1)){
                    flag = true;
                }
            }
            if(flag){
                String nodeKey = delegateTask.getTaskDefinitionKey();
                Map<String, Object> variables =  delegateTask.getVariables();
                Integer loopEnd = variables.get("_fortress_assignees_multiple_"+nodeKey+"_loopEnd")==null?1:Integer.parseInt(variables.get("_fortress_assignees_multiple_"+nodeKey+"_loopEnd").toString());
                Integer leaderIndex = variables.get("_fortress_assignees_multiple_"+nodeKey+"_leaderIndex")==null?1:Integer.parseInt(variables.get("_fortress_assignees_multiple_"+nodeKey+"_leaderIndex").toString());
                //非最终级别
                if(leaderIndex<loopEnd){
                    ++leaderIndex;
                    delegateTask.setVariable("_fortress_assignees_multiple_"+nodeKey+"_leaderIndex",leaderIndex+"");
                    delegateTask.setVariable("_fortress_assignees_multiple_"+nodeKey,variables.get("_fortress_assignees_multiple_"+nodeKey+"_"+leaderIndex));
                    //将流程切换到本节点
                    runtimeService.createChangeActivityStateBuilder()
                            .moveExecutionToActivityId(delegateTask.getExecutionId(), nodeKey).changeState();
                }
            }
        }
        if(StrUtil.isNotEmpty(delegateTask.getAssignee())){
            runtimeService.removeVariable(delegateTask.getExecutionId(),delegateTask.getAssignee());
        }
    }
}
